package cn.mesmile.emqtt.controller;

import cn.mesmile.emqtt.enums.MqttQosEnum;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author zb
 * @date 2021/7/14 21:46
 * @Description
 */
@Slf4j
@RequestMapping("/mqtt")
@RestController
public class WebHookController {
    // 判断客户端是否在线状态
    private Map<String,Boolean> clientStatus = new HashMap<>();

    @PostMapping("/webhook")
    public void get(@RequestBody Map<String,Object> params){
        log.info(">>>>>>>>> 触发webhook，请求数据为：{}", params);
        String action = (String) params.get("action");
        String clientId = (String) params.get("clientid");
        if (Objects.equals("client_connected", action)){
            log.info(">>>>>>>> 客户端成功[接入]：{}", params);
            clientStatus.put(clientId, true);

            // 自动订阅，相当于代理订阅 【这里只是连接成功，对客户端的会话还没有初始化成功】 所以订阅的方法请求的时候调用的是 异步方法
            autoSubAndUsub(clientId, "autotopic/#",MqttQosEnum.Qos2,true);
        }
        if (Objects.equals("client_disconnected", action)){
            log.info(">>>>>>>> 客户端[断开]：{}", params);
            clientStatus.put(clientId, false);
            // 自动取消订阅
            autoSubAndUsub(clientId, "autotopic/#",MqttQosEnum.Qos2,false);
        }
    }

    @GetMapping("/getStatus")
    public Map<String, Boolean> getStatus(){
        return this.clientStatus;
    }

    /**
     *  webhook 实现自动订阅和取消订阅
     * @param clientId
     * @param topicFilter
     * @param qosEnum
     * @param sub
     */
    public void autoSubAndUsub(String clientId, String topicFilter, MqttQosEnum qosEnum, boolean sub){
        RestTemplate restTemplate = new RestTemplateBuilder().basicAuthentication("admin", "public")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();

        Map<String, Object> params = new HashMap<>();
        params.put("clientid", clientId);
        params.put("topic", topicFilter);
        params.put("qos", qosEnum.value());

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(params, httpHeaders);
        if (sub){
            new Thread(() -> {
                String url = "/api/v4/mqtt/subscribe";
                ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, mapHttpEntity, String.class);
                log.info(">>>>>> 自动订阅的结果：{}", stringResponseEntity.getBody());
            }).start();
        } else {
            new Thread(() -> {
                String url = "/api/v4/mqtt/unsubscribe";
                ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, mapHttpEntity, String.class);
                log.info(">>>>>> 自动取消订阅的结果：{}", stringResponseEntity.getBody());
            }).start();
        }
    }

}
